<?php

namespace App\Controller\App;

use App\Base\BaseCache;
use App\Base\BaseConfig;
use App\Base\BaseController4Restful;
use App\Base\Format;
use App\Entity\User;
use App\Model\LazyCommon\UserModel;
use App\Repository\CategoryRepository;
use App\Repository\ConfigRepository;
use App\Repository\MoneyStaticRepository;
use App\Repository\UserRepository;
use App\Service\MoneyService;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

/**
 * @route("/app")
 */
class UserShareController extends BaseController4Restful
{
    /**
     * @Route("/user/share/info", name="AppUserShareInfo")
     */
    public function AppUserShareInfo()
    {
        $user = $this->needToBeUser();
        $data["user"] = $user;
        $regUrl = BaseConfig::__BASE_URL__ . $this->generateUrl("WapReg", array("phone" => $user->getPhone()));
        $shareCode =  BaseConfig::__BASE_URL__ . $this->generateUrl("Qr", array("code"=> $regUrl));
        $data["code"] = $shareCode;
        $data["shareUrl"] = $regUrl;
        $this->setGroups("home");
        return $this->json_out(200, "数据获取成功", $data);
    }


    /**
     * @Route("/user/share/reg/page", name="AppUserShareRegPage")
     */
    public function AppUserShareRegPage()
    {
        if (!$phone = $this->getParamRequired("a")) {
            die;
        }
        return $this->render("App/reg.html.twig", array("phone" => $phone));
    }



    /**
     * @Route("/user/share/reg/do", name="AppUserShareRegDo")
     */
    public function AppUserShareRegDo(UserRepository $userRepository,ConfigRepository $configRepository,MoneyService $moneyService)
    {
        if (!$phone = $this->getParamRequired("phone")) {
            return $this->json_out(201, "请输入手机号");
        }
        if (!$password = $this->getParamRequired("password")) {
            return $this->json_out(201, "请设置密码");
        }

        $findUser = $userRepository->findOneByPhone($phone);
        if ($findUser) {
            return $this->json_out(201, "手机号已注册，请下载App直接登录");
        }

        $user = new User();
        $user->setApiToken($phone)
            ->setPhone($phone)->setAvatar("/ApiCloud/assets/img/userHead.jpeg")->setPassword(md5($phone))
            ->setCreateAt(new \DateTime())
//            ->setName("用户_" . $phone);
            ->setName("用户_" . rand(1000,9999));
        if ($invite = $this->getParamRequired("invite")) {
            $parent = $userRepository->findOneByPhone($invite);
            $user->setParent( $parent );

            $moneys = $configRepository->getByK("INVITE_BONUS");
            $moneyArray = myExplodeNumbers($moneys);
            $curUser = $user;
            foreach ($moneyArray as $row) {
                $parent = $curUser->getParent();
                //增加上级奖励
                if ($parent) {
                    $moneyService->mod($parent,$row,MoneyService::__MONEY_JI_FEN__,161,"推广奖励",array());
                    $curUser = $parent;
                }else{
                    continue;
                }
            }


        }
        $this->myEm()->persist($user);
        $this->myEm()->flush();
        return $this->json_out(200, "注册成功，请下载APP登录");
    }
    /**
     * @Route("/user/share/sons", name="AppUserShareSons")
     */
    public function AppUserShareSons()
    {
        $user = $this->needToBeUser();
        $sons = $user->getSons();
        $data = [];
        //全部显示
//        $this->createTree($sons,$data,0);

        //只摘出一级和二级
        $sonson = [];
        foreach ($sons as $son) {
            $sonarr = $son->getSons();
            foreach ($sonarr as $one) {
                $sonson[] = $one;
            }
        }

        $this->setGroups("user");

        $data["level1"] = $sons;
        $data["level2"] = $sonson;
        return $this->json_out(200,"OK",$data);
    }
    public function getAllAdminMenuTree()
    {
        $root = $this->getAllAdminMenu();
        $this->createTree($root,$list);
        $data = array();
        $levels = [];
        if (!$list) {
            $list = [];
        }
        /**@var $en User */
        foreach ($list as $en) {

            if (!$en->getParent()){
                $level = 0;
            }else{
                $level = $levels[$en->getParent()->getId()] + 1;
            }
            $levels[$en->getId()] = $level;
            $prefix = "";
            if ($level > 0) {
                $prefix .="├";
                for ($i=0;$i<$level;$i++ ) {
                    $prefix .="────";
                }
            }
            $data[] = [
                "level" => $level,
                "data" => $en,
                "pre" => $prefix,
            ];
        }
        return $data;
    }

    function createTree($objectList , &$rst = [] ,$level = 0)
    {
        foreach ($objectList as $parent) {
            $rst[] = $parent;
            if ($sons= $parent->getSons()) {
                $this->createTree($sons,$rst,$level+1);
            }
        }
    }



    /**
     * @Route("/user/share/rank", name="AppUserShareRank")
     */
    public function AppUserShareRank(MoneyStaticRepository $repository)
    {
        if(!$page = $this->getParamRequired("page")){$page = 1;}
        $list=[];
        $qb = $repository->createQueryBuilder("S");
        $qb->where("S.moneyType = ".MoneyService::__MONEY_INVITE__);
        $qb->setMaxResults(10)->setFirstResult($page * 10 - 10);
        $qb->orderBy("S.money","DESC");
        $list=$qb->getQuery()->execute();
        $this->setGroups("static","user");
        return $this->json_out(200,"OK",$list);
    }
}
